/**
 * @module  cookie
 * @author  zfkun@msn.com
 */
ZF.add('cookie', function(Z) {

    var C = Z.Cookie = Z.Cookie || {},
        mix = Z.mix,

        doc = document,
        encode = encodeURIComponent,
        decode = decodeURIComponent;

    var C = Z.Cookie = Z.Cookie || {};

    C.write = function(key, value, options){
		value = encode(value);
		options = mix({}, options);
		
		if (isAvailable(options.domain)) {
            value += '; domain=' + options.domain;
        }

		if (isAvailable(options.path)) {
            value += '; path=' + options.path;
        }

        var date = options.duration;
		if (typeof(date) == 'number') {
			date = new Date();
			date.setTime(date.getTime() + options.duration * 86400000); // 86400000 = 24 * 60 * 60 * 1000
			value += '; expires=' + date.toGMTString();
		}

		if (options.secure) {
            value += '; secure';
        }
		
		//options.doc.cookie = key + '=' + value;
        doc.cookie = key + '=' + value;
	};
	
	C.read = function(key){
		var value;
        
        if (isAvailable(key)) {
            value = doc.cookie.match('(?:^|;)\\s*' + key.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1') + '=([^;]*)');
        }

		return value && value[1] ? decode(value[1]) : null;
	};
	
	C.dispose = function(key, options){
		this.write(key, '', mix({}, options, { duration : -1 }));
	};


    function isAvailable(value) {
        return typeof(value) == 'string' && value !== '';
    }
    
});